package com.aurora.CETManagementSystem.config;

import com.aurora.CETManagementSystem.mapper.AccountMapper;
import com.aurora.CETManagementSystem.pojo.Account;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

public class PermissionRealm extends AuthorizingRealm {

    @Resource
    AccountMapper accountMapper;

    @Override   //身份授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("test=>>>>身份授权----principals = " + principals);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        Account currentAccount = (Account) subject.getPrincipal(); //拿到User对象

        info.addStringPermission(currentAccount.getPermission());//设置当前用户的权限,从数据库里读取出来的.
        return info;


    }

    @Override   //身份验证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("test=>>>认证doGetAuthenticationInfo");

        System.out.println("test=>>>"+token);

        //获取Token
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        //连接真实数据库

        Account account = accountMapper.selectOne(new QueryWrapper<Account>().eq("username",userToken.getPrincipal()));


        if(account==null){  //没有这个人
            return null; //抛出异常 UnknownAccountException
        }

        //密码认证 Shiro也封装了
        //可以设置加密: MD5加密 MD5盐值加密
        return new SimpleAuthenticationInfo(account,account.getPassword(),"");
    }
}

